package com.msmall.community.team.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.msmall.base.pager.PaginationSupport;
import com.msmall.base.service.impl.BaseManagerImpl;
import com.msmall.base.util.ConstantDB;
import com.msmall.base.util.Constants;
import com.msmall.base.util.StringUtil;
import com.msmall.community.bbs.model.Topic;
import com.msmall.community.bbs.service.TopicManager;
import com.msmall.community.bbs.util.BbsUtil;
import com.msmall.community.common.Configuration;
import com.msmall.community.common.model.Message;
import com.msmall.community.common.service.MessageManager;
import com.msmall.community.common.util.FilterCharsUtil;
import com.msmall.community.team.dao.TeamDao;
import com.msmall.community.team.dao.TeamPropertyDao;
import com.msmall.community.team.dao.TeamTopicDao;
import com.msmall.community.team.dao.TeamUserDao;
import com.msmall.community.team.model.Team;
import com.msmall.community.team.model.TeamProperty;
import com.msmall.community.team.model.TeamTopic;
import com.msmall.community.team.model.TeamTopicModel;
import com.msmall.community.team.model.TeamUser;
import com.msmall.community.team.service.TeamManager;
import com.msmall.community.team.util.TeamUtil;
import com.msmall.community.user.model.UserInfo;
import com.msmall.community.user.service.UserManager;

public class TeamManagerImpl extends BaseManagerImpl<Team, Long> implements TeamManager{
	private static final Log log = LogFactory.getLog(TeamManagerImpl.class);
	private TeamDao teamDao;
	private TeamUserDao teamUserDao;
	private TeamPropertyDao teamPropertyDao;
	private TeamTopicDao teamTopicDao;
	private TopicManager topicManager;
	private UserManager userManager;
	private MessageManager messageManager;
	
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public void setTopicManager(TopicManager topicManager) {
		this.topicManager = topicManager;
	}

	public void setMessageManager(MessageManager messageManager) {
		this.messageManager = messageManager;
	}

	public void setTeamUserDao(TeamUserDao teamUserDao) {
		this.teamUserDao = teamUserDao;
	}

	public void setTeamDao(TeamDao teamDao) {
		this.teamDao = teamDao;
	}

	public void setTeamPropertyDao(TeamPropertyDao teamPropertyDao) {
		this.teamPropertyDao = teamPropertyDao;
	}

	public void setTeamTopicDao(TeamTopicDao teamTopicDao) {
		this.teamTopicDao = teamTopicDao;
	}
	/**
	 * 验证组信息是否合法
	 *  0合法；1 组名已经存在；2组名不合法; 3组名太短；4组名太长；5组描述不合法；6组描述太短；7组描述太长
	 */
	public int validateTeam(Team team){
		int nameResult = validateTeamName(team.getName());
		if(nameResult != 0)
			return nameResult;
		int descResult = validateTeamDescription(team.getDescription());
		if(descResult != 0)
			return descResult;
		if(team.getTeamid() == null || team.getTeamid().longValue() == 0l){
			try {
				Team temp = teamDao.loadTeamByName(team.getName());
				if(temp != null)
					return 1;
			} catch (Exception e) {
				log.error(e);
			}
		}
		return 0;
	}
	/**
	 * 验证组名
	 * 0合法；2组名不合法; 3组名太短；4组名太长；
	 */
	public int validateTeamName(String name){
		int min = Configuration.getIntegerValue(Configuration.TEAM_NAME_MIN_CHARS);
		int max = Configuration.getIntegerValue(Configuration.TEAM_NAME_MAX_CHARS);
		if(StringUtil.nullOrBlank(name)){
			return 3;
		}
		if(name.length() < min){
			return 3;
		}
		if(name.length() > max){
			return 4;
		}
		boolean titleC = FilterCharsUtil.containsFilterChars(name);
		if(titleC){
			return 2;
		}
		return 0 ;
	}
	
	/**
	 * 验证组名
	 * 0合法；5组描述不合法；6组描述太短；7组描述太长
	 */
	public int validateTeamDescription(String description){
		int min = Configuration.getIntegerValue(Configuration.TEAM_DESCRIPTION_MIN_CHARS);
		int max = Configuration.getIntegerValue(Configuration.TEAM_DESCRIPTION_MAX_CHARS);
		if(StringUtil.nullOrBlank(description)){
			return 6;
		}
		if(description.length() < min){
			return 6;
		}
		if(description.length() > max){
			return 7;
		}
		boolean titleC = FilterCharsUtil.containsFilterChars(description);
		if(titleC){
			return 5;
		}
		return 0 ;
	}
	/**
	 * 检查用户能否创建组，目前只检查创建数量限制
	 * @param userid
	 */
	public boolean canCreateTeam(Long userid){
		try {
			List<Team> teams = loadTeamsByUserPosition(userid, TeamUser.POSITION_CHAIRMAN);
			if(teams == null){
				return true;
			}else if(teams.size() < Configuration.getIntegerValue(Configuration.TEAM_DEFAULT_CREATE_COUNT)){
				return true;
			}
		} catch (Exception e) {
		}
		return false;
	}
	
	/**
	 * 通过用户ID和职位，查找到此用户所在组
	 * eg : postion = TeamUser.Position_chairman用户所有创建的组
	 * @param userid
	 */
	public List<Team> loadTeamsByUserPosition(Long userid, Integer position) throws Exception{
		try {
			return teamDao.loadTeamsByUserPosition(userid, position);
		} catch (Exception e) {
			log.error(e);
			throw e;
		}
	}
	/**
	 * 通过用户ID，查找到此用户所在组
	 * @param userid
	 * @throws Exception 
	 */
	public List<Team> loadTeamsByUserStatus(Long userid, Integer status) throws Exception{
		try {
			return teamDao.loadTeamsByUserStatus(userid, status);
		} catch (Exception e) {
			log.error(e);
			throw e;
		}
	}
	/**
	 * 申请创建组
	 * @param userid 申请人
	 * @param name组名称
	 * @param description 组描述
	 * @author zhzy
	 */
	public boolean createTeam(Long userid, String name, String description){
		try{
			Team team = new Team();
			team.setCreateTime(new Date());
			team.setDescription(description);
			team.setName(name);
			team.setStatus(Team.STATUS_TOBE_AUDIT);
			team.setRank(Team.RANK_NORMAL);
			team.setMemberCount(1);
			team.setLogo(ConstantDB.TEAM_DEFAULT_LOGO);
			team = (Team) teamDao.saveObject(team);
			
			TeamUser tUser = new TeamUser();
			tUser.setUserid(userid);
			tUser.setTeamid(team.getTeamid());
			tUser.setPosition(TeamUser.POSITION_CHAIRMAN);
			tUser.setStatus(TeamUser.STATUS_NORMAL);
			tUser.setApplyPaper("");
			tUser.setTeamNickname(team.getName());
			tUser.setNickname(userManager.getByUserid(userid).getNickname());
			tUser.setCreateTime(new Date());
			teamDao.saveObject(tUser);
			
			TeamProperty property1 = new TeamProperty();
			property1.setPropertyKey(TeamProperty.KEY_APPLY_AUDIT);
			property1.setPropertyValue(TeamProperty.VALUE_APPLY_AUDIT_NO);
			property1.setTeam(team);
			TeamProperty property2 = new TeamProperty();
			property2.setPropertyKey(TeamProperty.KEY_AUTHRIZED_USER);
			property2.setPropertyValue("");
			property2.setTeam(team);
			TeamProperty property3 = new TeamProperty();
			property3.setPropertyKey(TeamProperty.KEY_SHARED_TEAM);
			property3.setPropertyValue("");
			property3.setTeam(team);
			TeamProperty property4 = new TeamProperty();
			property4.setPropertyKey(TeamProperty.KEY_VISIT);
			property4.setPropertyValue(TeamProperty.VALUE_DEFAULT_ALL);
			property4.setTeam(team);
			
			Set<TeamProperty> properties = new HashSet<TeamProperty>();
			properties.add(property1);
			properties.add(property2);
			properties.add(property3);
			properties.add(property4);
			team.setProperties(properties);
			teamDao.saveObject(team);
		}catch(Exception e){
			return false;
		}
		return true;
	}
	
	/**
	 * 更新组信息，只能更新组名，组描述,只有创建者有此权限
	 * 0 修改成功 1 权限不够 9其他错误
	 * @param userid
	 * @param team
	 * @author zhzy
	 */
	public int updateTeam(Long userid, Long teamid, String name, String description){
		try{
			TeamUser tUser = teamUserDao.load(userid, teamid);
			if(tUser.getPosition().intValue() == TeamUser.POSITION_CHAIRMAN.intValue()){
				Team team = (Team) teamDao.get(Team.class, teamid);
				team.setName(name);
				team.setDescription(description);
				teamDao.saveObject(team);
				return 0;
			}else{
				return 1;
			}
		}catch(Exception e){
			return 9;
		}
	}
	/**
	 * 只有创建者能修改组LOGO
	 */
	public Team saveTeamLogo(File logo, String logoFileName, String uat, Long userid, Long teamid){
		try{
			TeamUser creator = getTeamCreator(teamid);
			if(creator.getUserid().compareTo(userid) != 0){
				return null;
			}
			String[] pathinfo = TeamUtil.saveImage(logo, logoFileName, userid, uat, teamid);
			Team team = (Team) teamDao.get(Team.class, teamid);
			team.setLogo(pathinfo[0]+pathinfo[1]);
			team = (Team) teamDao.saveObject(team);
			return team;
		}catch(Exception e){
			log.error(e);
		}
		return null;
	}
	/**
	 * 前台创建者销毁组
	 *  0 修改成功 1 权限不够 9其他错误
	 */
	public int destroyTeam(Long userid, Long teamid){
		try{
			TeamUser tUser = teamUserDao.load(userid, teamid);
			if(tUser.getPosition().intValue() == TeamUser.POSITION_CHAIRMAN.intValue()){
				removeTeam(teamid);
				return 0;
			}else{
				return 1;
			}
		}catch(Exception e){
			return 9;
		}
	}
	/**
	 * 后台管理员销毁组
	 * 0 修改成功 1 权限不够 9其他错误
	 */
	public int adminDestroyTeam(Long userid, Long teamid){
		try{
			removeTeam(teamid);
			return 0;
		}catch(Exception e){
			return 9;
		}
	}
	private void removeTeam(Long teamid) throws Exception{
		try{
			Team team = (Team) teamDao.get(Team.class, teamid);
			team.setStatus(Team.STATUS_CLOSED);
			teamDao.saveObject(team);
		}catch(Exception e){
			throw e;
		}
	}
	
	/**
	 * 管理员审核 申请创建的组是否能够成立
	 * @param userid
	 * @param teamid
	 * @param audit true成立
	 * @author zhzy
	 */
	public boolean adminAuditTeam(Long userid, Long teamid, boolean audit){
		try{
			Team team = (Team) teamDao.get(Team.class, teamid);
			if(audit)
				team.setStatus(Team.STATUS_NORMAL);
			else
				team.setStatus(Team.STATUS_AUDIT_FAILURE);
			teamDao.saveObject(team);
			return true;
		}catch(Exception e){
			return false;
		}
	}
	/**
	 * 组管理员审核用户的申请
	 *0 修改成功 1 权限不够 9其他错误
	 * @param audit true通过 false 不通过
	 * @author zhzy
	 */
//	public int audit(Long userid, Long tuid, boolean audit) {
//		try{
//			TeamUser tUser = (TeamUser) teamUserDao.get(TeamUser.class, tuid);
//			TeamUser chairman = teamUserDao.load(userid, tUser.getTeamid());
//			if(chairman.getPosition().intValue() == TeamUser.POSITION_CHAIRMAN.intValue() || chairman.getPosition().intValue() == TeamUser.POSITION_VICE_CHAIRMAN){
//				if(audit){
//					tUser.setStatus(TeamUser.STATUS_NORMAL);
//					Team team = (Team) teamDao.get(Team.class, tUser.getTeamid());
//					team.setMemberCount(team.getMemberCount() + 1);
//				}
//				else{
//					tUser.setStatus(TeamUser.STATUS_REJECT);
//				}
//				teamUserDao.saveObject(tUser);
//				return 0;
//			}else{
//				return 1;
//			}
//			
//		}catch(Exception e){
//			return 9;
//		}
//	}
	
	/**
	 * 组长，副组长修改组员信息, 仅修改职位/状态/组昵称
	 */
	//TODO 人数
	public void saveTeamUser(Long managerid, TeamUser teamUser){
		TeamUser old = (TeamUser) teamUserDao.get(TeamUser.class, teamUser.getTuid());
		TeamUser currManager = getTeamUser(managerid, teamUser.getTeamid());
		Team team = (Team) teamDao.get(Team.class, teamUser.getTeamid());
		if(currManager.getPosition().intValue() == TeamUser.POSITION_CHAIRMAN){//组长
			if(teamUser.getUserid().compareTo(managerid) == 0){//修改自己信息
			}else if(teamUser.getPosition() == TeamUser.POSITION_VICE_CHAIRMAN){//添加/修改副组长信息
				if(old.getPosition() == TeamUser.POSITION_VICE_CHAIRMAN){//修改
					if(teamUser.getStatus().compareTo(TeamUser.STATUS_NORMAL) != 0){
						if(old.getStatus().compareTo(teamUser.getStatus()) != 0 && teamUser.getStatus().compareTo(TeamUser.STATUS_NORMAL) == 0){
							team.setMemberCount(team.getMemberCount() + 1);
							teamDao.saveObject(team);
							messageManager.joinTeamAcceptMessage(managerid, teamUser.getUserid(), teamUser.getTeamid());
						}else if(old.getStatus().compareTo(teamUser.getStatus()) != 0 && teamUser.getStatus().compareTo(TeamUser.STATUS_REJECT) == 0){
							messageManager.joinTeamRejectMessage(managerid, teamUser.getUserid(), teamUser.getTeamid());
						}
						if(old.getPosition().compareTo(teamUser.getPosition()) != 0){
							messageManager.teamPositionMessage(managerid, teamUser.getUserid(), teamUser.getTeamid());
						}
						old.setStatus(teamUser.getStatus());
						old.setPosition(TeamUser.POSITION_NORMAL);
					}
				}else{//添加副组长
					List<TeamUser> normalManagers = getTeamManagers(teamUser.getTeamid(), false);
					if(normalManagers != null && normalManagers.size() == Configuration.getIntegerValue(Configuration.TEAM_DEFAULT_VICE_CHAIRMAN_COUNT)){
						if(old.getPosition().compareTo(teamUser.getPosition()) != 0){
							messageManager.teamPositionMessage(managerid, teamUser.getUserid(), teamUser.getTeamid());
						}
						old.setPosition(TeamUser.POSITION_NORMAL);
					}else{
						if(old.getPosition().compareTo(teamUser.getPosition()) != 0){
							messageManager.teamPositionMessage(managerid, teamUser.getUserid(), teamUser.getTeamid());
						}
						old.setPosition(TeamUser.POSITION_VICE_CHAIRMAN);
					}
					if(teamUser.getStatus().compareTo(TeamUser.STATUS_NORMAL) != 0){
						if(old.getPosition().compareTo(teamUser.getPosition()) != 0){
							messageManager.teamPositionMessage(managerid, teamUser.getUserid(), teamUser.getTeamid());
						}
						old.setPosition(TeamUser.POSITION_NORMAL);
					}
					if(old.getStatus().compareTo(teamUser.getStatus()) != 0 && teamUser.getStatus().compareTo(TeamUser.STATUS_NORMAL) == 0){
						team.setMemberCount(team.getMemberCount() + 1);
						teamDao.saveObject(team);
						messageManager.joinTeamAcceptMessage(managerid, teamUser.getUserid(), teamUser.getTeamid());
					}else if(old.getStatus().compareTo(teamUser.getStatus()) != 0 && teamUser.getStatus().compareTo(TeamUser.STATUS_REJECT) == 0){
						messageManager.joinTeamRejectMessage(managerid, teamUser.getUserid(), teamUser.getTeamid());
					}
					old.setStatus(teamUser.getStatus());
				}
			}else{
				if(old.getStatus().compareTo(teamUser.getStatus()) != 0 && teamUser.getStatus().compareTo(TeamUser.STATUS_NORMAL) == 0){
					team.setMemberCount(team.getMemberCount() + 1);
					teamDao.saveObject(team);
					messageManager.joinTeamAcceptMessage(managerid, teamUser.getUserid(), teamUser.getTeamid());
				}else if(old.getStatus().compareTo(teamUser.getStatus()) != 0 && teamUser.getStatus().compareTo(TeamUser.STATUS_REJECT) == 0){
					messageManager.joinTeamRejectMessage(managerid, teamUser.getUserid(), teamUser.getTeamid());
				}
				if(old.getPosition().compareTo(teamUser.getPosition()) != 0){
					messageManager.teamPositionMessage(managerid, teamUser.getUserid(), teamUser.getTeamid());
				}
				old.setPosition(teamUser.getPosition());
				old.setStatus(teamUser.getStatus());
			}
		}else if(currManager.getPosition().compareTo(TeamUser.POSITION_VICE_CHAIRMAN) == 0 && currManager.getStatus().compareTo(TeamUser.STATUS_NORMAL) == 0){//副组长
			if(old.getPosition() == TeamUser.POSITION_CHAIRMAN){
				//不可修改组长信息
				return;
			}else if(old.getPosition().compareTo(TeamUser.POSITION_VICE_CHAIRMAN) == 0 && teamUser.getUserid().compareTo(managerid) != 0){
				//不可修改其他副组长信息
				return;
			}else if(old.getPosition().compareTo(TeamUser.POSITION_NORMAL) == 0){
				old.setStatus(teamUser.getStatus());
				if(old.getStatus().compareTo(teamUser.getStatus()) != 0 && teamUser.getStatus().compareTo(TeamUser.STATUS_NORMAL) == 0){
					team.setMemberCount(team.getMemberCount() + 1);
					teamDao.saveObject(team);
					messageManager.joinTeamAcceptMessage(managerid, teamUser.getUserid(), teamUser.getTeamid());
				}else if(old.getStatus().compareTo(teamUser.getStatus()) != 0 && teamUser.getStatus().compareTo(TeamUser.STATUS_REJECT) == 0){
					messageManager.joinTeamRejectMessage(managerid, teamUser.getUserid(), teamUser.getTeamid());
				}
			}
		}else{
			return;
		}
		if(!old.getNickname().equals(teamUser.getNickname())){//修改昵称
			String newNickname = FilterCharsUtil.replaceAllFilterChars(teamUser.getNickname(), null);
			old.setNicknameHistory(old.getNicknameHistory() + "," + old.getNickname());
			old.setNickname(newNickname);
		}
		teamUserDao.saveObject(old);
	}
	
	/**
	 *  用户修改在组中的昵称
	 */
	public TeamUser saveTeamUserNickname(Long userid, Long teamid, String nickname){
		TeamUser old = getTeamUser(userid, teamid);
		if(nickname == null || "".equals(nickname))
			return old;
		if(!old.getNickname().equals(nickname)){//修改昵称
			String newNickname = FilterCharsUtil.replaceAllFilterChars(nickname, null);
			old.setNicknameHistory(old.getNicknameHistory() + "," + old.getNickname());
			old.setNickname(newNickname);
			old = (TeamUser) teamUserDao.saveObject(old);
		}
		return old;
	}
	/**
	 *  组长/副组长才具有权限邀请
	 * 邀请用户加入组，目前只支持按昵称邀请，如果存在多个人同一个昵称，则全部邀请(目前不能，当前系统昵称唯一)
	 * 如果被邀请用户申请过加入/是组成员了：
	 * 1正常 不处理
	 * 2申请中 改为1正常状态
	 * 3拒绝 ,改为1正常状态 
	 * 4受邀请 ，重新发送邀请信息
	 * 9被屏蔽 ，改为4受邀请 发送邀请信息
	 * 邀请后发送社区消息到用户系统MESSAGE
	 * @param userid 邀请人ID
	 * @param invite 被邀请人信息
	 */
	public void inviteUser(Long userid, Long teamid, String invite){
		TeamUser teamUser = getTeamUser(userid, teamid);
		if(teamUser.getPosition().compareTo(TeamUser.POSITION_CHAIRMAN) ==0 
				|| (teamUser.getPosition().compareTo(TeamUser.POSITION_VICE_CHAIRMAN)==0 && teamUser.getStatus().compareTo(TeamUser.STATUS_NORMAL)==0)){
			// 组长/副组长才具有权限邀请
			List<UserInfo> users = userManager.getByNickname(invite);
			if(users == null || users.size() <= 0){
				return;
			}
			Team team = (Team) teamDao.get(Team.class, teamid);
			for(int j=0; j < users.size(); j++){
				UserInfo user = users.get(j);
				TeamUser old = getTeamUser(user.getUserid(), teamid);
				if(old != null){
					if(old.getStatus().compareTo(TeamUser.STATUS_APPLYING) == 0){
						old.setStatus(TeamUser.STATUS_NORMAL);
					}else if(old.getStatus().compareTo(TeamUser.STATUS_REJECT) == 0){
						old.setStatus(TeamUser.STATUS_NORMAL);
					}else if(old.getStatus().compareTo(TeamUser.STATUS_FORBIDDEN) == 0){
						messageManager.inviteTeamMessage(userid, user.getUserid(), teamid);
						old.setStatus(TeamUser.STATUS_INVITE);
					}else if(old.getStatus().compareTo(TeamUser.STATUS_INVITE) == 0){
						messageManager.inviteTeamMessage(userid, user.getUserid(), teamid);
					}
					old = (TeamUser) teamUserDao.saveObject(old);
				}else{
					TeamUser tUser = new TeamUser();
					tUser.setApplyPaper("被邀请");
					tUser.setNickname(user.getNickname());
					tUser.setNicknameHistory("");
					tUser.setPosition(TeamUser.POSITION_NORMAL);
					tUser.setTeamid(teamid);
					tUser.setTeamNickname(team.getName());
					tUser.setTeamNicknameHistory("");
					tUser.setUserid(user.getUserid());
					tUser.setCreateTime(new Date());
					tUser.setStatus(TeamUser.STATUS_INVITE);
					tUser = (TeamUser) teamUserDao.saveObject(tUser);
					messageManager.inviteTeamMessage(userid, user.getUserid(), teamid);
				}
			}
		}
	}
	/**
	 * 用户同意加入组
	 * 增加组成员数量
	 */
	public void inviteAgress(Long userid, Long teamid, Long messageid){
		TeamUser tUser = getTeamUser(userid, teamid);
		tUser.setStatus(TeamUser.STATUS_NORMAL);
		teamUserDao.saveObject(tUser);
		Team team = (Team) teamDao.get(Team.class, teamid);
		team.setMemberCount(team.getMemberCount() + 1);
		teamDao.saveObject(team);
		messageManager.setRead(messageid);
	}
	
	/**
	 * 用户不同意加入组
	 * 如果用户的申请被拒绝了，那么删除记录
	 */
	public void inviteReject(Long userid, Long teamid, Long messageid){
		TeamUser tUser = getTeamUser(userid, teamid);
		teamUserDao.remove(tUser);
		messageManager.remove(Message.class, messageid);
	}
	/**
	 * 设置组访问权限，只有创建者可以设置
	 * 0 修改成功 1 权限不够 9其他错误
	 * @author zhzy
	 */
	public int setTeamVisit(Long userid, Long teamid,String value){
		try{
			TeamUser chairman = teamUserDao.load(userid, teamid);
			if(chairman.getPosition().intValue() == TeamUser.POSITION_CHAIRMAN.intValue()){
				TeamProperty property = teamPropertyDao.load(teamid, TeamProperty.KEY_VISIT);
				if(property == null){
					Team team = (Team) teamDao.get(Team.class, teamid);
					property = new TeamProperty();
					property.setTeam(team);
					property.setPropertyKey(TeamProperty.KEY_VISIT);
				}
				property.setPropertyValue(value);
				teamPropertyDao.saveObject(property);
				return 0;
			}else{
				return 1;
			}
			
		}catch(Exception e){
			return 9;
		}
	}
	/**
	 * 获得组的访问设置，如果没有，默认所有人都可以访问
	 * @param teamid
	 */
	public TeamProperty getTeamVisit(Long teamid){
		TeamProperty property = null;
		try {
			property = teamPropertyDao.load(teamid, TeamProperty.KEY_VISIT);
		} catch (Exception e) {
		}
		if(property == null){
			Team team = (Team) teamDao.get(Team.class, teamid);
			property = new TeamProperty();
			property.setTeam(team);
			property.setPropertyKey(TeamProperty.KEY_VISIT);
			property.setPropertyValue(TeamProperty.VALUE_DEFAULT_ALL);
			property = (TeamProperty) teamPropertyDao.saveObject(property);
		}
		return property;
	}
	/**
	 * 设置组成员申请是否需要审核，只有创建者可以设置
	 *  0 修改成功 1 权限不够 9其他错误
	 * @author zhzy
	 */
	public int setTeamApplyAudit(Long userid, Long teamid, String value){
		try{
			TeamUser chairman = teamUserDao.load(userid, teamid);
			if(chairman.getPosition().intValue() == TeamUser.POSITION_CHAIRMAN.intValue()){
				TeamProperty property = teamPropertyDao.load(teamid, TeamProperty.KEY_APPLY_AUDIT);
				if(property == null){
					Team team = (Team) teamDao.get(Team.class, teamid);
					property = new TeamProperty();
					property.setTeam(team);
					property.setPropertyKey(TeamProperty.KEY_APPLY_AUDIT);
				}
				property.setPropertyValue(value);
				teamPropertyDao.saveObject(property);
				return 0;
			}else{
				return 1;
			}
			
		}catch(Exception e){
			return 9;
		}
	}
	/**
	 * 获得 组成员申请是否需要审核， 如果没有，默认添加一天数据，并且值为不需要审核
	 * @param teamid
	 * @return
	 * @author zhzy
	 */
	public TeamProperty getTeamApplyAudit(Long teamid){
		TeamProperty property = null;
		try {
			property = teamPropertyDao.load(teamid, TeamProperty.KEY_APPLY_AUDIT);
		} catch (Exception e) {
		}
		if(property == null){
			Team team = (Team) teamDao.get(Team.class, teamid);
			property = new TeamProperty();
			property.setTeam(team);
			property.setPropertyKey(TeamProperty.KEY_APPLY_AUDIT);
			property.setPropertyValue(TeamProperty.VALUE_APPLY_AUDIT_NO);
			property = (TeamProperty) teamPropertyDao.saveObject(property);
		}
		return property;
	}
	/**
	 * 设置组的共享组，只有创建者可以设置
	 *  0 修改成功 1 权限不够 9其他错误
	 * @author zhzy
	 */
	public int addSharedTeam(Long userid, Long teamid, Long sharedid){
		try{
			TeamUser chairman = teamUserDao.load(userid, teamid);
			if(chairman.getPosition().intValue() == TeamUser.POSITION_CHAIRMAN.intValue()){
				TeamProperty property = getSharedTeam(teamid);
				property.setPropertyValue(property.getPropertyValue() + "," + sharedid);
				teamPropertyDao.saveObject(property);
				return 0;
			}else{
				return 1;
			}
			
		}catch(Exception e){
			return 9;
		}
	}
	/**
	 * 获得组的共享组
	 * @param teamid
	 * @return
	 * @author zhzy
	 */
	public TeamProperty getSharedTeam(Long teamid){
		TeamProperty property = null;
		try {
			property = teamPropertyDao.load(teamid, TeamProperty.KEY_SHARED_TEAM);
		} catch (Exception e) {
		}
		if(property == null){
			Team team = (Team) teamDao.get(Team.class, teamid);
			property = new TeamProperty();
			property.setTeam(team);
			property.setPropertyKey(TeamProperty.KEY_SHARED_TEAM);
			property.setPropertyValue("");
			property = (TeamProperty) teamPropertyDao.saveObject(property);
		}
		return property;
	}
	
	/**
	 * 获得组的授权访问用户
	 * @param teamid
	 * @return
	 * @author zhzy
	 */
	public TeamProperty getAuthrizedUser(Long teamid){
		TeamProperty property = null;
		try {
			property = teamPropertyDao.load(teamid, TeamProperty.KEY_AUTHRIZED_USER);
		} catch (Exception e) {
		}
		if(property == null){
			Team team = (Team) teamDao.get(Team.class, teamid);
			property = new TeamProperty();
			property.setTeam(team);
			property.setPropertyKey(TeamProperty.KEY_AUTHRIZED_USER);
			property.setPropertyValue("");
			property = (TeamProperty) teamPropertyDao.saveObject(property);
		}
		return property;
	}
	
	/**
	 * 设置组的授权访问用户，只有创建者和管理者可以设置
	 *  0 修改成功 1 权限不够 9其他错误
	 * @author zhzy
	 */
	public int addAuthrizedUser(Long userid, Long teamid, Long authid){
		try{
			TeamUser chairman = teamUserDao.load(userid, teamid);
			if(chairman.getPosition().intValue() == TeamUser.POSITION_CHAIRMAN.intValue() || chairman.getPosition().intValue() == TeamUser.POSITION_VICE_CHAIRMAN.intValue()){
				TeamProperty property = getAuthrizedUser(teamid);
				property.setPropertyValue(property.getPropertyValue() + "," + authid);
				teamPropertyDao.saveObject(property);
				return 0;
			}else{
				return 1;
			}
			
		}catch(Exception e){
			return 9;
		}
	}
	/**
	 * 获得组的创建者 
	 */
	public TeamUser getTeamCreator(Long teamid){
		try {
			return teamUserDao.getTeamCreator(teamid);
		} catch (Exception e) {
			return null;
		}
	}
	/**
	 * 获得组的管理者,并且状态是TEAM.STATUS_NORMAL
 	 * creator: true 包括创建者 false:不包括创建者 
	 */
	public List<TeamUser> getTeamManagers(Long teamid, boolean creator){
		try {
			return teamUserDao.getTeamManagers(teamid, creator);
		} catch (Exception e) {
			return null;
		}
	}
	/**
	 * 获得组的普通成员,并且状态是TEAM.STATUS_NORMAL，不包括创建者和管理者 
	 */
	public List<TeamUser> getTeamMembers(Long teamid){
		try {
			return teamUserDao.getTeamMembers(teamid);
		} catch (Exception e) {
			return null;
		}
	}
	/**
	 * 根据组员状态获得组用户信息,包括组的创建人，管理者，普通组员
	 * type TeamUser.STATUS_xx,如果为-1则获得所有用户
	 * @author zhzy
	 */
	public List<TeamUser> getMembers(Long teamid, int type) {
		try {
			return teamUserDao.getMembers(teamid, type);
		} catch (Exception e) {
			return null;
		}
	}
	public TeamUser getTeamUser(Long userid, Long teamid){
		try {
			return teamUserDao.load(userid, teamid);
		} catch (Exception e) {
			log.error(e);
			return null;
		}
	}
	/**
	 * 申请入组
	 * 首先检查是否已经申请了，如果已经申请了，如果状态是：
	 * 1正常 不处理
	 * 2申请中 不处理 
	 * 3 拒绝 ,重新改为申请
	 * 4受邀请 ，改为1正常状态
	 * 9被屏蔽 ，不处理
	 */
	public TeamUser join(Long userid, Long teamid, String applyPaper) {
		TeamUser old = getTeamUser(userid, teamid);
		if(old != null){
			if(old.getStatus().compareTo(TeamUser.STATUS_REJECT) == 0){
				old.setStatus(TeamUser.STATUS_APPLYING);
				joinTeamMessage(userid, teamid);
			}else if(old.getStatus().compareTo(TeamUser.STATUS_INVITE) == 0){
				old.setStatus(TeamUser.STATUS_NORMAL);
			}
			old = (TeamUser) teamUserDao.saveObject(old);
			return old;
		}else{
			TeamProperty property = getTeamApplyAudit(teamid);
			UserInfo user = userManager.getByUserid(userid);
			Team team = (Team) teamDao.get(Team.class, teamid);
			TeamUser tUser = new TeamUser();
			tUser.setApplyPaper(applyPaper);
			tUser.setNickname(user.getNickname());
			tUser.setNicknameHistory("");
			tUser.setPosition(TeamUser.POSITION_NORMAL);
			tUser.setTeamid(teamid);
			tUser.setTeamNickname(team.getName());
			tUser.setTeamNicknameHistory("");
			tUser.setUserid(userid);
			tUser.setCreateTime(new Date());
			
			if(property.getPropertyValue().equals(TeamProperty.VALUE_APPLY_AUDIT_NO)){
				tUser.setStatus(TeamUser.STATUS_APPLYING);
			}else{
				tUser.setStatus(TeamUser.STATUS_NORMAL);
			}
			tUser = (TeamUser) teamUserDao.saveObject(tUser);
			joinTeamMessage(userid, teamid);
			return tUser;
		}
	}
	/**
	 * 用户申请加入群组时，通知组长/副组长
	 */
	private void joinTeamMessage(Long userid, Long teamid){
		List<Long> receivers = new ArrayList<Long>();
		List<TeamUser> ms = getTeamManagers(teamid, true);
		for(int i=0; i< ms.size(); i++){
			receivers.add(ms.get(i).getUserid());
		}
		messageManager.joinTeamMessage(userid, receivers, teamid);
		
	}
	/**
	 *  退组
	 */
	public boolean leave(Long userid, Long teamid) {
		try {
			TeamUser tUser = teamUserDao.load(userid, teamid);
			if(tUser.getPosition().intValue() == TeamUser.POSITION_CHAIRMAN){
				return false;
			}
			Team team = (Team) teamDao.get(Team.class, teamid);
			teamUserDao.remove(tUser);
			team.setMemberCount(team.getMemberCount() - 1);
			messageManager.leaveTeamUserMessage(userid, teamid);
			return true;
		} catch (Exception e) {
			return false;
		}
		
	}
	
	/**
	 * 检查用户对组的某个属性是否有权限;目前KEY 只为TeamProperty.KEY_VISIT
	 * @param userid
	 * @param teamid
	 * @param key
	 * @author zhzy
	 */
	public boolean checkAuthrized(Long userid, Long teamid, String key){
		TeamProperty property = getTeamVisit(teamid);
		String visit = property.getPropertyValue();
		if(visit == null || "".equals(visit) || TeamProperty.VALUE_DEFAULT_ALL.equals(visit)){
			return true;
		}
		if(TeamProperty.VALUE_DEFAULT_AUTHRIZED_USER.equals(visit)){
			TeamProperty authUser = getAuthrizedUser(teamid);
			String ids = authUser.getPropertyValue();
			if(ids.indexOf(userid.toString()) != -1)
				return true;
			else 
				return false;
		}
		if(TeamProperty.VALUE_DEFAULT_TEAM.equals(visit)){
			TeamProperty sharedTeam = getSharedTeam(teamid);
			String ids = sharedTeam.getPropertyValue();
			if(ids == null || ids.trim().length() ==0){
				return false;
			}
			String[] idx = ids.split(",");
			for(int i=0; i < idx.length; i++){
				String id = idx[i].trim();
				try {
					TeamUser tUser = teamUserDao.load(userid, Long.valueOf(id));
					if(tUser != null)
						return true;
				}  catch (Exception e) {
					continue;
				}
			}
		}
		if(TeamProperty.VALUE_DEFAULT_NONE.equals(visit)){
			return false;
		}
		if(TeamProperty.VALUE_DEFAULT_ONLY_MEMBER.equals(visit)){
			try {
				TeamUser tUser = teamUserDao.load(userid, teamid);
				if(tUser != null)
					return true;
			} catch (Exception e) {
			}
			return false;
		}
		return false;
	}
	/**
	 * 获得用户在组中的关系;首先判断用户是否是组员，然后判断用户状态是否正常
	 * 如果是组成员 并且状态正常 返回TeamUser.POSITION_
	 * 如果陌生人 返回 -1
	 * 如果状态不正常 返回 -2
	 */
	public int getPosition(Long userid, Long teamid){
		try {
			TeamUser tUser = teamUserDao.load(userid, teamid);
			if(tUser == null){
				return -1;
			}
			if(tUser.getStatus().intValue() == TeamUser.STATUS_NORMAL){
				return tUser.getPosition();
			}else{
				return -2;
			}
		} catch (Exception e) {
		}
		return -1;
	}
	/**
	 * 在组内发表话题 
	 * @author zhzy
	 */
	public void newTeamTopic(Long userid, Long teamid,Short original, String title, String content, String userAgentType,String sharePublic, Long boardid, boolean sharedTeam){
		Topic topic = new Topic();
		topic.setOriginal(original);
		topic.setTitle(title);
		topic.setContent(content);
		if(ConstantDB.TEAM_TOPIC_SHARE_PUBLIC.equals(sharePublic)){
			topic = topicManager.saveTopic(topic, boardid, userid, userAgentType);
		}else{
			sharePublic = ConstantDB.TEAM_TOPIC_SHARE_PUBLIC_UN;
			boardid = BbsUtil.getBBSDefaultBoard();
			topic = topicManager.saveTopicDisabled(topic, boardid, userid, userAgentType);
		}
		TeamTopic tTopic = new TeamTopic();
		tTopic.setTeamid(teamid);
		tTopic.setTopicid(topic.getTopicId());
		tTopic.setUserid(userid);
		tTopic.setEnabled(ConstantDB.AVALIABLE);
		tTopic.setSharePublic(sharePublic);
		if(sharedTeam){
			TeamProperty property = getSharedTeam(teamid);
			tTopic.setSharedTeam("," + property.getPropertyValue() + ",");
		}else{
			tTopic.setSharedTeam("");
		}
		teamTopicDao.saveObject(tTopic);
	}
	
	/**
	 *  组长/副组长删除组话题
	 *  enabled修改， 如果发布到社区，不影响社区应用 
	 */
	public void deleteTeamTopic(Long userid, Long ttid){
		TeamTopic tTopic = (TeamTopic) teamTopicDao.get(TeamTopic.class, ttid);
		if(tTopic != null){
			TeamUser tUser = getTeamUser(userid, tTopic.getTeamid());
			if(tUser.getPosition().intValue() == TeamUser.POSITION_CHAIRMAN || (tUser.getPosition().intValue() == TeamUser.POSITION_VICE_CHAIRMAN && tUser.getStatus().intValue() == TeamUser.STATUS_NORMAL)){
				tTopic.setEnabled(ConstantDB.UNAVALIABLE);
				teamTopicDao.saveObject(tTopic);
			}
		}
	}
	/**
	 *  获得组的话题列表，包括由分享获得的共享话题, page.item TeamTopicModel
	 *  根据发表时间排序
	 */
	public void getPaginationByTeam(PaginationSupport page, Long teamid){
		String queryString = "select o from TeamTopic o, Topic t where o.topicid= t.topicId and ( o.teamid=" + teamid + " or o.sharedTeam like '%," + teamid +",%'" + ") and o.enabled=" + ConstantDB.AVALIABLE + " order by t.createTime desc";
		page.setQueryString(queryString);
		getPagination(page);
		List<TeamTopic> list = page.getItems();
		List<TeamTopicModel> models = new ArrayList<TeamTopicModel>();
		for(int i=0; i<list.size();i++){
			TeamTopicModel model = new TeamTopicModel();
			TeamTopic tTopic = list.get(i);
			try {
				Topic topic = topicManager.getTopic(tTopic.getTopicid());
				model.setTopic(topic);
				model.setEntity(tTopic);
				models.add(model);
			} catch( Exception e) {
				continue;
			}
		}
		page.setItems(models);
	}
	
	public TeamTopicModel getByTeamTopicid(Long ttid){
		TeamTopicModel model = new TeamTopicModel();
		TeamTopic tTopic = (TeamTopic) teamTopicDao.get(TeamTopic.class, ttid);
		try {
			Topic topic = topicManager.getTopic(tTopic.getTopicid());
			model.setTopic(topic);
			model.setEntity(tTopic);
		} catch( Exception e) {
		}
		return model;
	}
	/**
	 * 获得所有可用组
	 * @param page
	 * @author zhzy
	 */
	public void getAvaliableTeam(PaginationSupport page){
		String queryString = " from Team where status=" + Team.STATUS_NORMAL;
		page.setQueryString(queryString);
		getPagination(page);
	}
	/**
	 * 通过组名获得组
	 */
	public Team loadTeamByName(String name){
		try {
			return teamDao.loadTeamByName(name);
		} catch (Exception e) {
			log.error(e);
			return null;
		}
	}
	
	/**
	 * 获得一个组的所有属性
	 */
	public List<TeamProperty> getAllProperties(Long teamid){
		try {
			return teamPropertyDao.loadAllProperties(teamid);
		} catch (Exception e) {
			log.error(e);
			return null;
		}
	}
}
